package org.xs.web.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import javax.servlet.ServletContext;

import org.xs.web.http.S;


 
public class Resources {

	 public static InputStream getResourceAsStream(String resource, ServletContext servletContext) 
	 {
	      String stripped = resource.startsWith("/") ? 
	            resource.substring(1) : resource;
	   
	      InputStream stream = null; 

	      if (servletContext!=null) {
	         try {
	            stream = servletContext.getResourceAsStream(resource);
	         } catch (Exception e) {       
	             //
	         }
	      }
	      
	  
	      return stream;
	   }
	 
	 public static File getResource(String path,ServletContext servletContext){
		 try {
			return new File(servletContext.getRealPath(""));
		} catch (Exception e) {
			 
		}
		return null;
	 }
	 
	public static InputStream getResourceAsStream(String resource){
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		InputStream inputStream = null;
		
		if(classLoader != null){
			inputStream = classLoader.getResourceAsStream(resource);
		}
		if(inputStream == null){
			inputStream = S.class.getResourceAsStream(resource);
		}
		if(inputStream == null){
			inputStream = S.class.getClassLoader().getResourceAsStream(resource);
		}
		
		return inputStream;
	}
	
	
	public static URL getResource(String resource){
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		URL url = null;
		
		if(classLoader != null){
			url = classLoader.getResource(resource);
		}
		if(url == null){
			url = S.class.getResource(resource);
		}
		if(url == null){
			url = S.class.getClassLoader().getResource(resource);
		}
		
		return url;
	}
	
	
	public static void closeStream(InputStream stream){
		if(stream == null){
			return ;
		}
		try {
			stream.close();
		} catch (IOException e) {
			 
		}
	}
}
